package cn.com.shuyangyang.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.shuyangyang.domain.LoginLog;

/**
 * 登录过滤器，防止未登录访问系统中的内容
 * @author ShuYangYang
 * E-Mail:shuyangyang@aliyun.com
 * http://www.shuyangyang.com.cn
 * Date:2015年12月6日下午12:48:25
 *
 */
public class LoginFilter implements Filter{
	
	Logger	logger	= LoggerFactory.getLogger(LoginFilter.class);

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		logger.info("登录过滤器初始化……");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
	      // 获得在下面代码中要用的request,response,session对象
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        HttpServletResponse servletResponse = (HttpServletResponse) response;
        HttpSession session = servletRequest.getSession();

        // 获得用户请求的URI
        String path = servletRequest.getRequestURI();
        //System.out.println(path);
        
        // 从session里取信息
        LoginLog loginLog = (LoginLog)session.getAttribute("loginLogInfo");

        /*创建类Constants.java，里面写的是无需过滤的页面
        for (int i = 0; i < Constants.NoFilter_Pages.length; i++) {

            if (path.indexOf(Constants.NoFilter_Pages[i]) > -1) {
                chain.doFilter(servletRequest, servletResponse);
                return;
            }
        }*/
        
        // 登录页面和资源文件无需过滤
        if(path.indexOf("/Web-Admin/login.jsp") > -1
        		||path.indexOf("/Web-Admin/js") > -1
        		||path.indexOf("/Web-Admin/images") > -1) {
            chain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 判断如果没有取到员工信息,就跳转到登陆页面
        if (loginLog == null || "".equals(loginLog)) {
            // 跳转到登陆页面
            servletResponse.sendRedirect(((HttpServletRequest)request).getContextPath()+"/Web-Admin/login.jsp");
        } else {
            // 已经登陆,继续此次请求
            chain.doFilter(request, response);
        }
	}

	@Override
	public void destroy() {
		logger.info("登录过滤器销毁……");
	}

}
